import React, { useCallback, useEffect, useMemo, useState } from "react";
import { LibAppView } from "../../../../lib";
import { Card, Form, theme, Table, Button,App } from "antd";
import { AdvancedSearch } from "../../Component/AdvancedSearch";
import { FormattedMessage, useIntl } from "react-intl";
import { Edit } from "./Edit";
import { CONST_SYSTEM_MODULE } from "../../../../config/constant";
import styles from "../User/styles.module.scss";

const Language = LibAppView.withService({
    reqEndPoints: [{
        endPoint: "setting.langaugeList",
        name: "languageList"
    }]
})((props) => {
    const intl = useIntl();
    const { modal, message} = App.useApp();
    const [ loading, setLoading ] = useState(false);
    const [ listData, setListData ] = useState([]);
    const [ formState, setFormState ] = useState({
        open: false,
        data: null
    });
    const [ searchData, setSearchData ] = useState({});
    const [ tempState ] = useState({ isMount: false });
    const sysModuleList = useMemo(() => CONST_SYSTEM_MODULE.map((item) => ({
        ...item,
        i18nKey: item.label,
        label: intl.formatMessage({ id: item.label })
    })),[intl.locale])
    const LangaugeField: Admin.IAdvancedField<Admin.ISelectOption[]> = {
        type: "Select",
        label: "system.module",
        name: "module",
        placeholder: "admin.layout.select.placeholder",
        data: [
            { label: intl.formatMessage({id: "admin.pages.languages.all"}),value: null },
            ...(sysModuleList as unknown) as any[]
        ]
    };
    
    const SearchFields: Admin.IAdvancedField[] = [
        LangaugeField,
        {
            type: "Input",
            label: "admin.pages.language.name",
            name: "name",
            placeholder: "admin.layout.input.placeholder",
            props: { autoComplete: "off" }
        },
        {
            type: "Input",
            label: "admin.pages.languages.content",
            name: "content",
            placeholder: "admin.layout.input.placeholder",
            props: { autoComplete: "off" }
        }
    ];
    const onSearchChange = (values: any) => {
        setSearchData({...values});
    };
    const [ columns ] = useState([
        {
            title: <FormattedMessage id="system.module"/>,
            dataIndex: "module",
            width: 120,
            render: (text: string) => {
                const module = sysModuleList.find((item) => item.value === text);
                return module ? <FormattedMessage id={module.i18nKey}/> : text;
            }
        },
        {
            title: <FormattedMessage id="admin.pages.language.name"/>,
            dataIndex: "name",
            width: 140
        }, {
            title: <FormattedMessage id="admin.pages.language.english"/>,
            dataIndex: "en_gb"
        }, {
            title: <FormattedMessage id="admin.pages.language.chinese"/>,
            dataIndex: "cn_zh"
        }, {
            title: <FormattedMessage id="admin.pages.createUser"/>,
            dataIndex: "createUserName",
            width: 140
        },  {
            title: <FormattedMessage id="admin.pages.createTime"/>,
            dataIndex: "create_time",
            width: 180
        }, {
            title: <FormattedMessage id="admin.pages.updateUser"/>,
            dataIndex: "updateUserName",
            width: 140
        },{
            title: <FormattedMessage id="admin.pages.updateTime"/>,
            dataIndex: "update_time",
            width: 180
        },{
            title: <FormattedMessage id="admin.pages.language.operate"/>,
            dataIndex: "id",
            width: 100,
            render: (id: number, data: any) => {
                return (<div className={styles.tableOperate}>
                    <Button size="small" onClick={() => setFormState({ open: true, data: {...data} })}><FormattedMessage id="admin.pages.operate.edit"/></Button>
                    <Button size="small" onClick={()=>{
                         modal.confirm({
                            title: intl.formatMessage({id:"admin.layout.modal.question"}),
                            content: intl.formatMessage({id:"admin.pages.language.msg.delete"}),
                            okText: intl.formatMessage({id:"admin.layout.modal.confirm"}),
                            cancelText: intl.formatMessage({id:"admin.layout.modal.cancel"}),
                            onOk: () => {
                                setLoading(true);
                                props.withServiceApi.send({
                                    endPoint: "setting.languageDelete",
                                    data
                                }).then(() => {
                                    onRefresh();
                                }).catch((err) => {
                                    console.error(err);
                                    message.error(err.message || "未知错误");
                                    setLoading(false);
                                });
                            }
                        });
                    }}><FormattedMessage id="admin.pages.operate.delete"/></Button>
                </div>);
            }
        }
    ]);
    const onRefresh = useCallback(() => {
        setLoading(true);
        props.withServiceApi.send({
            endPoint: "setting.langaugeList",
            data: searchData
        }).then(({ data }: any) => {
            setListData(data);
            setLoading(false);
        }).catch((err) => {
            console.error(err);
            setLoading(false);
        });
    }, [searchData]);
    useEffect(() => {
        if(props.responseData.afterApiResponse) {
            setListData((props.responseData as any).languageList?.data || []);
        }
    }, []);
    useEffect(() => {
        if(tempState.isMount) {
            onRefresh();
        }
        tempState.isMount = true;
    }, [searchData, onRefresh])
    return (<Card style={{ width: "100%", minHeight: "76vh" }}>
            <AdvancedSearch collapse onChange={onSearchChange} fields={SearchFields}/>
            <div style={{marginBottom: 20}}>
                <Button type="primary" onClick={() => setFormState({ open: true, data: null })}>
                    <FormattedMessage id="admin.pages.operate.add"/>
                </Button>
            </div>
            <div style={{overflowX: "auto"}}>
                <Table loading={loading} dataSource={listData} columns={columns} scroll={{ x: 1600 }} pagination={false} bordered/>
            </div>
            <Edit open={formState.open} moduleList={sysModuleList} data={formState.data} onClose={(success) => {
                setFormState({ open: false, data: null });
                success && onRefresh();
            }}/>
        </Card>
    );
});

export default Language;